package com.sgb.kjwl.view.ui.fragment.transport;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsAndCarsBinding;
import com.sgb.kjwl.model.entity.transport.TabEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.home.SearchActivity4;
import com.sgb.kjwl.view.ui.activity.home.SearchActivity5;
import com.sgb.kjwl.view.ui.activity.home.TransportSearchActivity;
import com.sgb.kjwl.view.ui.adapter.transport.SimpleTabAdapter;
import com.sgb.kjwl.view.ui.fragment.machine.CarInfoFragment;
import com.sgb.link.event.LeaseEvent;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 物流搜素
 */
public class GoodsCarsFragment extends AppLazyFragment {

    private FragmentGoodsAndCarsBinding binding;
    private ArrayList<Fragment> mFragments;
    String[] titles = {"找货", "找车"};

    public int currentChildTab;
    private String searchText;
    private ArrayList<TabEntity> mTabs;
    private SimpleTabAdapter mAdapter;
    boolean searchGoods, searchCar;
    private String mKeyWord;
    private boolean isRefresh = false;

    public GoodsCarsFragment() {

    }

    public static GoodsCarsFragment newInstance() {
        GoodsCarsFragment fragment = new GoodsCarsFragment();
        return fragment;
    }

    public static GoodsCarsFragment newInstance(String keyWord) {
        GoodsCarsFragment fragment = new GoodsCarsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("KEY_WORD", keyWord);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mKeyWord = getArguments().getString("KEY_WORD");
        }
        if (getActivity() instanceof SearchActivity5) {
            mKeyWord = ((SearchActivity5) getActivity()).getKeyWord();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods_and_cars, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @Override
    public void onVisible() {
        if (getActivity() instanceof SearchActivity5) {
            String keyWord = ((SearchActivity5) getActivity()).getKeyWord();
            if (!TextUtils.equals(mKeyWord, keyWord)) {
                isRefresh = true;
                mKeyWord = keyWord;
                initData();
            }
        }
    }

    @Override
    protected void onLazyLoad() {

    }

    private void initData() {
        if (isRefresh) {
            isRefresh = false;
            ((CarInfoFragment) mFragments.get(1)).refreshChildView(mKeyWord);
            ((SearchTransportGoodsFragment) mFragments.get(0)).refreshChildView(mKeyWord);
            return;
        }

        mTabs = new ArrayList<>();
        mTabs.add(new TabEntity("找货", true, 0, 99));
        mTabs.add(new TabEntity("找车", true, 0, 99));

        mAdapter = new SimpleTabAdapter(mTabs);
        binding.rvSearchTab.setLayoutManager(new GridLayoutManager(getActivity(), 2));

        binding.rvSearchTab.setAdapter(mAdapter);

        if (mFragments == null) {
            mFragments = new ArrayList<>();
        }
        mFragments.clear();
        mFragments.add(SearchTransportGoodsFragment.newInstance(mKeyWord));
        mFragments.add(CarInfoFragment.newInstance(mKeyWord));

        SlidingFragmentPagerAdapter mAdapetr = new SlidingFragmentPagerAdapter(getChildFragmentManager(), mFragments, titles);
        binding.viewPager.setAdapter(mAdapetr);
        binding.viewPager.setOffscreenPageLimit(titles.length - 1);
        // binding.tablayout.setViewPager(binding.viewPager, titles);
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                currentChildTab = i;
                mAdapter.setSelectIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mAdapter.setSelectIndex(position);
            binding.viewPager.setCurrentItem(position);
            postToSearch();
        });
    }


    private void postToSearch() {
        if (getCurrentChildTab() == 0 && searchGoods) {
            searchGoods = false;
            EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_GOODS).setMessageData(searchText));
        } else if (getCurrentChildTab() == 1 && searchCar) {
            searchCar = false;
            EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.SEARCH_CARS).setMessageData(searchText));
        }
    }

    public int getCurrentChildTab() {
        return currentChildTab;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseEvent event) {
        if (event.getMessageTag() == EventConstant.SEARCH_GOOODS_CARS) {
            searchText = (String) event.getMessageData();
            if (this.getActivity() instanceof SearchActivity4 || this.getActivity() instanceof TransportSearchActivity) {
                searchGoods = true;
                searchCar = true;
                postToSearch();
            }
            EventBus.getDefault().removeStickyEvent(event);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_COUNT) {
            if (mAdapter != null && mTabs != null && mTabs.size() > 0) {
                mTabs.get(0).setNumber(event.getCount());
                mAdapter.notifyDataSetChanged();
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_CAR_COUNT) {
            if (mAdapter != null && mTabs != null && mTabs.size() > 0) {
                mTabs.get(1).setNumber(event.getCount());
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public void refreshChildView() {
        if (getActivity() instanceof SearchActivity5) {
            mKeyWord = ((SearchActivity5) getActivity()).getKeyWord();
        }
        isRefresh = true;
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
